﻿using System;
using System.Collections.Generic;
using System.Text;
using FLTools.ComponentModel;
using FLCore;
using System.Xml;
using System.Threading;
using System.Net.Mail;
using System.Net;
using System.IO;
using System.Web;
using System.Data;
using System.Collections;

namespace FLRuntime
{
    public static class Email
    {
        private static string _sender = "SendToEmailSender";
        private static string _flowName = "SendToEmailFlowName";
        private static string _activityName = "SendToEmailActivityName";
        //private static string _content = "SendToEmailContent";
        private static string _description = "SendToEmailDescription";
        private static string _dateTime = "SendToEmailDateTime";
        private static string _hyperLink = "SendToEmailHyperLink";
        private static string _hyperLink2 = "SendToEmailHyperLink2";
        private static string _overTime = "InstanceOverTime";
        //private static string _overTime2 = "InstanceOverTime2";
        private static string _header = "CommentTableHeader";
        private static string _status = "InstanceStatus";

        private static SmtpClient _client;
        private static MailMessage _message;

        /// <summary>
        /// 取得签核意见
        /// </summary>
        /// <param name="flInstanceId">流程Id</param>
        /// <param name="clientInfo">ClientInfo</param>
        /// <returns></returns>
        private static string GetComments(string flInstanceId, object[] clientInfo)
        {
            string comments = string.Empty;
            DataSet ds = Global.GetComments(flInstanceId, clientInfo);
            if (ds != null)
            {
                Hashtable statusTable = new Hashtable();
                string status = SysMsg.GetSystemMessage((SYS_LANGUAGE)(((object[])(clientInfo[0]))[0]), "FLRuntime", "InstanceManager", _status);
                string[] ss1 = status.Split(",".ToCharArray());
                foreach (string s1 in ss1)
                {
                    if (string.IsNullOrEmpty(s1))
                    {
                        continue;
                    }

                    string[] ss2 = s1.Split(":".ToCharArray());
                    if (ss2.Length != 2)
                    {
                        continue;
                    }
                    statusTable.Add(ss2[0], ss2[1]);
                }


                string header = SysMsg.GetSystemMessage((SYS_LANGUAGE)(((object[])(clientInfo[0]))[0]), "FLRuntime", "InstanceManager", _header);
                string[] columns = header.Split(",".ToCharArray());

                comments += "<TR>";
                foreach (string column in columns)
                {
                    if (string.IsNullOrEmpty(column))
                        continue;

                    comments += string.Format("<TD>{0}</TD>", column);
                }
                comments += "</TR>";

                foreach (DataRow row in ds.Tables[0].Rows)
                {
                    comments += "<TR>";
                    foreach (DataColumn column in row.Table.Columns)
                    {
                        object obj = row[column];
                        if (column.ColumnName.Trim().ToUpper() == "STATUS")
                        {
                            if (obj != null && obj != DBNull.Value)
                            {
                                if (statusTable.ContainsKey(obj.ToString()))
                                {
                                    obj = statusTable[obj.ToString()];
                                }
                            }
                        }

                        if (obj == null || obj == DBNull.Value || obj.ToString() == string.Empty)
                        {
                            obj = "&nbsp;";
                        }

                        comments += string.Format("<TD>{0}</TD>", obj);
                    }
                    comments += "</TR>";
                }
            }

            return comments;
        }

        private static string GetPresentation(string presenationCT)
        {
            if (!string.IsNullOrEmpty(presenationCT))
            {
                StringBuilder builder = new StringBuilder();
                string[] presents = presenationCT.Split(';');
                foreach (string present in presents)
                {
                    string[] keyandvalue = present.Split('=');
                    if (keyandvalue.Length > 1)
                    {
                        builder.Append("<TR>");
                        builder.Append("<TD>");
                        builder.Append(keyandvalue[0]);
                        builder.Append("</TD>");
                        builder.Append("<TD COLSPAN=7>");
                        builder.Append(keyandvalue[1]);
                        builder.Append("</TD>");
                        builder.Append("</TR>");
                    }
                }
                return builder.ToString();
            }
            return string.Empty;
        }


        /// <summary>
        /// 发送Email
        /// </summary>
        /// <param name="flInstance">流程</param>
        /// <param name="flInstanceParms">流程参数</param>
        /// <param name="keyValues">宿主筛选条件</param>
        /// <param name="clientInfo">ClientInfo</param>
        public static void SendTo(FLInstance flInstance, object[] flInstanceParms, object[] keyValues, object[] clientInfo)
        {
            string sendFrom = string.Empty;
            string password = string.Empty;
            string smtp = string.Empty;

            List<FLActivity> nextFLActivities = flInstance.NextFLActivities;
            List<string> tmpList = new List<string>();
            foreach (FLActivity flActivity in nextFLActivities)
            {
                if (!(flActivity is IEventWaiting) && !(flActivity is IFLNotifyActivity))
                {
                    continue;
                }

                if (flActivity is IEventWaiting)
                {
                    IEventWaiting nextFLActivity = (IEventWaiting)flActivity;
                    if (nextFLActivity.SendEmail)
                    {
                        tmpList.Add(nextFLActivity.Name);
                    }
                }
                else if(flActivity is IFLNotifyActivity)
                {
                    IFLNotifyActivity nextFLActivity = (IFLNotifyActivity)flActivity;
                    if (nextFLActivity.SendEmail)
                    {
                        tmpList.Add(nextFLActivity.Name);
                    }
                }
            }
            if (tmpList.Count == 0)
                return;

            string tableName = ((IFLRootActivity)flInstance.RootFLActivity).TableName;
            string flowDesc = ((IFLRootActivity)flInstance.RootFLActivity).Description;
            string sUserId = ((object[])clientInfo[0])[1].ToString();
            string sUserName = Global.GetUserName(sUserId, clientInfo);

            XmlDocument doc = new XmlDocument();
            if (File.Exists("Workflow.xml"))
                doc.Load("Workflow.xml");
            else
                return;

            bool active = false;
            XmlNode nodeActive = doc.ChildNodes[0].SelectSingleNode("Active");
            if (nodeActive != null)
            {
                active = Convert.ToBoolean(nodeActive.InnerText);
            }
            if (!active)
            {
                return;
            }
            

            XmlNode nodeEmail = doc.ChildNodes[0].SelectSingleNode("Email");
            if (nodeEmail != null)
            {
                sendFrom = nodeEmail.InnerText;
            }
            else
            {
                return;
            }

            XmlNode nodePassword = doc.ChildNodes[0].SelectSingleNode("Password");
            if (nodePassword != null)
            {
                password = GetPwdString(nodePassword.InnerText);
            }
            else
            {
                return;
            }

            XmlNode nodeSMTP = doc.ChildNodes[0].SelectSingleNode("SMTP");
            if (nodeSMTP != null)
            {
                smtp = nodeSMTP.InnerText;
            }
            else
            {
                return;
            }

            foreach (FLActivity flActivity in nextFLActivities)
            {
                List<string> sendToes = new List<string>();
                if (!(flActivity is IEventWaiting) && !(flActivity is IFLNotifyActivity))
                {
                    continue;
                }

                bool sm = false;
                if (flActivity is IEventWaiting)
                {
                    sm = ((IEventWaiting)flActivity).SendEmail;
                }
                else if(flActivity is IFLNotifyActivity)
                {
                    sm = ((IFLNotifyActivity)flActivity).SendEmail;
                }

                if (sm)
                {
                    FLActivity nextFLActivity = flActivity;
                    int plusApprove = 0;
                    if (nextFLActivity is IFLStandActivity)
                    {
                        plusApprove = Convert.ToInt32(((IFLStandActivity)nextFLActivity).PlusApprove);
                    }
                    else if (nextFLActivity is IFLApproveActivity)
                    {
                        plusApprove = Convert.ToInt32(((IFLApproveActivity)nextFLActivity).PlusApprove);
                    }
                    else if (nextFLActivity is IFLApproveBranchActivity)
                    {
                        FLActivity approve = flInstance.RootFLActivity.GetFLActivityByName(((IFLApproveBranchActivity)nextFLActivity).ParentActivity);
                        plusApprove = Convert.ToInt32(((IFLApproveActivity)approve).PlusApprove);
                    }

                    string users = string.Empty;
                    string email = string.Empty;
                    SendToKind sk = SendToKind.Applicate;
                    string sr = string.Empty;
                    string sf = string.Empty;
                    string su = string.Empty;
                    string fn = string.Empty;
                    string wfn = string.Empty;
                    NavigatorMode nm = NavigatorMode.Normal;
                    FLNavigatorMode fnm = FLNavigatorMode.Notify;
                    if (flActivity is IEventWaiting)
                    {
                        sk = ((IEventWaiting)flActivity).SendToKind;
                        sr = ((IEventWaiting)flActivity).SendToRole;
                        su = ((IEventWaiting)flActivity).SendToUser;
                        sf = ((IEventWaiting)flActivity).SendToField;
                        wfn = string.IsNullOrEmpty(((IEventWaiting)flActivity).WebFormName)
                            ? ((IFLRootActivity)flInstance.RootFLActivity).WebFormName
                            : ((IEventWaiting)flActivity).WebFormName;
                        nm = ((IEventWaiting)flActivity).NavigatorMode;
                        fnm = ((IEventWaiting)flActivity).FLNavigatorMode;
                    }
                    else if (flActivity is IFLNotifyActivity)
                    {
                        sk = ((IFLNotifyActivity)flActivity).SendToKind;
                        sr = ((IFLNotifyActivity)flActivity).SendToRole;
                        su = ((IFLNotifyActivity)flActivity).SendToUser;
                        sf = ((IFLNotifyActivity)flActivity).SendToField;
                        wfn = string.IsNullOrEmpty(((IFLNotifyActivity)flActivity).WebFormName)
                                     ? ((IFLRootActivity)flInstance.RootFLActivity).WebFormName
                                     : ((IFLNotifyActivity)flActivity).WebFormName;
                        nm = ((IFLNotifyActivity)flActivity).NavigatorMode;
                        fnm = ((IFLNotifyActivity)flActivity).FLNavigatorMode;
                    }


                    List<string> roleIds = new List<string>();
                    // string roleId = string.Empty;
                    string orgKind = ((IFLRootActivity)flInstance.RootFLActivity).OrgKind;
                    if (flInstance.IsPlusApprove)
                    {
                        string q = flInstanceParms[8].ToString();
                        string[] qq = q.Split(";".ToCharArray());
                        foreach (string r in qq)
                        {
                            if (!string.IsNullOrEmpty(r))
                            {
                                roleIds.Add(r);
                            }
                        }
                    }
                    else
                    {
                        if (sk == SendToKind.Applicate)
                        {
                            email = Global.GetUserEmail(flInstance.Creator, clientInfo);
                            if (email != null && email != string.Empty)
                                sendToes.Add(email);
                        }
                        else if (sk == SendToKind.Role)
                        {
                            string q = sr;
                            string[] qq = q.Split(";".ToCharArray());

                            // roleId = qq[0].Trim();
                            roleIds.Add(qq[0].Trim());
                        }
                        else if (sk == SendToKind.ApplicateManager)
                        {
                            List<string> roles = Global.GetRoleIdsByUserId(flInstance.Creator, clientInfo);
                            if (roles.Count > 0)
                            {
                                roleIds.Add(Global.GetManagerRoleId(roles[0], orgKind, clientInfo));
                            }
                        }
                        else if (sk == SendToKind.Manager)
                        {
                            if (flInstance.FLDirection == FLDirection.GoToBack)
                            {
                                // roleId = ((IEventWaitingExecute)nextFLActivity).RoleId;
                                roleIds.Add(((IEventWaitingExecute)nextFLActivity).RoleId);
                            }
                            else
                            {
                                // roleId = Global.GetManagerRoleId(flInstanceParms[5].ToString(), orgKind, clientInfo);
                                roleIds.Add(Global.GetManagerRoleId(flInstanceParms[5].ToString(), orgKind, clientInfo));
                            }
                        }
                        else if (sk == SendToKind.RefRole)
                        {
                            if (nextFLActivity is FLStandActivity && ((ISupportFLDetailsActivity)nextFLActivity).SendToId2 != string.Empty)
                            {
                                // roleId = ((ISupportFLDetailsActivity)nextFLActivity).SendToId2;
                                roleIds.Add(((ISupportFLDetailsActivity)nextFLActivity).SendToId2);
                            }
                            else
                            {
                                // roleId = Global.GetRoleIdByRefRole(sf, tableName, keyValues[1].ToString(), clientInfo);
                                roleIds.Add(Global.GetRoleIdByRefRole(sf, tableName, keyValues[1].ToString(), clientInfo));
                            }
                        }
                        else if (sk == SendToKind.RefManager)
                        {
                            if (flInstance.FLDirection == FLDirection.GoToBack)
                            {
                                // roleId = ((IEventWaitingExecute)nextFLActivity).RoleId;
                                roleIds.Add(((IEventWaitingExecute)nextFLActivity).RoleId);
                            }
                            else
                            {
                                if (nextFLActivity is IFLApproveBranchActivity &&
                                    ((FLApproveActivity)flInstance.RootFLActivity.GetFLActivityByName(((IFLApproveBranchActivity)nextFLActivity).ParentActivity)).I > 1)
                                {
                                    // roleId = Global.GetManagerRoleId(flInstanceParms[5].ToString(), orgKind, clientInfo);
                                    roleIds.Add(Global.GetManagerRoleId(flInstanceParms[5].ToString(), orgKind, clientInfo));
                                }
                                else
                                {
                                    string sendToField = sf;
                                    string values = keyValues[1].ToString();

                                    string s = Global.GetRoleIdByRefRole(sendToField, tableName, values, clientInfo);
                                    // roleId = Global.GetManagerRoleId(s.ToString(), orgKind, clientInfo);
                                    roleIds.Add(Global.GetManagerRoleId(s.ToString(), orgKind, clientInfo));
                                }
                            }
                        }
                        else if (sk == SendToKind.RefUser)
                        {
                            string id = Global.GetRoleIdByRefRole(sf, tableName, keyValues[1].ToString(), clientInfo, true);

                            if (!string.IsNullOrEmpty(id))
                            {
                                string[] listusers = id.Split(';');
                                foreach (string user in listusers)
                                {
                                    if (user.Trim().Length > 0)
                                    {
                                        email = Global.GetUserEmail(user, clientInfo);
                                        if (email != null && email != string.Empty)
                                            sendToes.Add(email);
                                    }
                                }
                            }
                        }
                        else if (sk == SendToKind.User)
                        {
                            string[] listusers = su.Split(';');
                            foreach (string user in listusers)
                            {
                                if (user.Trim().Length > 0)
                                {
                                    email = Global.GetUserEmail(user, clientInfo);
                                    if (email != null && email != string.Empty)
                                        sendToes.Add(email);
                                }
                            }
                        }

                        else if (flActivity is IFLNotifyActivity & sk == SendToKind.AllRoles)
                        {
                            foreach (string r in flInstance.RL)
                            {
                                if (string.IsNullOrEmpty(r))
                                    continue;

                                string[] rr = r.Split(":".ToCharArray());
                                if (rr[0] == "R")
                                {
                                    roleIds.Add(rr[1]);
                                }
                                else
                                {
                                    roleIds.Add(r);
                                }

                                roleIds.Add(string.Format("U:{0}", flInstance.Creator));
                            }
                        }
                        else
                        {
                            // roleId = flInstanceParms[5].ToString();
                            roleIds.Add(flInstanceParms[5].ToString());
                        }
                    }

                    List<string> userIds = new List<string>();
                    //if (roleId != null && roleId != string.Empty)
                    //{
                    //    userIds = Global.GetUsersIdsByRoleId(roleId, clientInfo);
                    //}
                    List<string> tempIds = new List<string>();
                    foreach (string r in roleIds)
                    {
                        string[] rr = r.Split(":".ToCharArray());
                        if (rr.Length > 1)
                        {
                            tempIds.Add(rr[1]);
                        }

                        tempIds.AddRange(Global.GetUsersIdsByRoleId(r, clientInfo));
                    }
                    foreach (string u in tempIds)
                    {
                        if (userIds.Contains(u))
                            continue;

                        userIds.Add(u);
                    }

                    foreach (string userId in userIds)
                    {
                        if (users.Length != 0)
                        {
                            users += ",";
                        }
                        users += userId;

                        email = Global.GetUserEmail(userId, clientInfo);
                        if (email != null && email != string.Empty)
                            sendToes.Add(email);
                    }


                    if (sendToes.Count == 0)
                    {
                        continue;
                    }
                    string body = string.Empty;

                    body += "<TABLE BORDER=1>";

                    XmlNode nodeSender = doc.ChildNodes[0].SelectSingleNode("Sender");
                    if ((nodeSender != null && Convert.ToBoolean(nodeSender.InnerText)) || nodeSender == null)
                    {
                        body += "<TR>";
                        body += "<TD WIDTH=150>";
                        body += SysMsg.GetSystemMessage((SYS_LANGUAGE)(((object[])(clientInfo[0]))[0]), "FLRuntime", "InstanceManager", _sender);
                        body += "</TD>";
                        body += "<TD  COLSPAN=7>";
                        body += string.Format("[{0}]{1}", sUserId, sUserName);
                        body += "</TD>";
                        body += "</TR>";
                    }

                    XmlNode nodeFlowName = doc.ChildNodes[0].SelectSingleNode("FlowName");
                    if ((nodeFlowName != null && Convert.ToBoolean(nodeFlowName.InnerText)) || nodeFlowName == null)
                    {
                        body += "<TR>";
                        body += "<TD>";
                        body += SysMsg.GetSystemMessage((SYS_LANGUAGE)(((object[])(clientInfo[0]))[0]), "FLRuntime", "InstanceManager", _flowName);
                        body += "</TD>";
                        body += "<TD  COLSPAN=7>";
                        body += string.IsNullOrEmpty(flowDesc) ? "&nbsp;" : flowDesc;
                        body += "</TD>";
                        body += "</TR>";
                    }

                    XmlNode nodeActivityName = doc.ChildNodes[0].SelectSingleNode("ActivityName");
                    if ((nodeActivityName != null && Convert.ToBoolean(nodeActivityName.InnerText)) || nodeActivityName == null)
                    {
                        body += "<TR>";
                        body += "<TD>";
                        body += SysMsg.GetSystemMessage((SYS_LANGUAGE)(((object[])(clientInfo[0]))[0]), "FLRuntime", "InstanceManager", _activityName);
                        body += "</TD>";
                        body += "<TD  COLSPAN=7>";
                        body += nextFLActivity.Name;
                        body += "</TD>";
                        body += "</TR>";
                    }

                    string presenationCT = null;
                    XmlNode nodeContent = doc.ChildNodes[0].SelectSingleNode("Content");
                    if ((nodeContent != null && Convert.ToBoolean(nodeContent.InnerText)) || nodeContent == null)
                    {
                        string presentFields = ((IFLRootActivity)flInstance.RootFLActivity).PresentFields;
                        string keys = keyValues[0].ToString();
                        string presenation = keyValues[1].ToString();
                        presenationCT = Global.GetFormPresentCT(tableName, keys, presenation, presentFields, clientInfo);

                        body += GetPresentation(presenationCT);
                    }

                    XmlNode nodeDescription = doc.ChildNodes[0].SelectSingleNode("Description");
                    if ((nodeDescription != null && Convert.ToBoolean(nodeDescription.InnerText)) || nodeDescription == null)
                    {
                        string remark = flInstance.FLFlag == 'X' ? "Reject(system)" : flInstanceParms[4].ToString();
                        //added by lily 2009-5-11 如果審核意見中有換行會報錯
                        remark = remark.Replace("\r\n", "<BR/>");
                        body += "<TR>";
                        body += "<TD>";
                        body += SysMsg.GetSystemMessage((SYS_LANGUAGE)(((object[])(clientInfo[0]))[0]), "FLRuntime", "InstanceManager", _description);
                        body += "</TD>";
                        body += "<TD  COLSPAN=7>";
                        body += string.IsNullOrEmpty(remark) ? "&nbsp;" : remark;
                        body += "</TD>";
                        body += "</TR>";
                    }

                    XmlNode nodeDateTime = doc.ChildNodes[0].SelectSingleNode("DateTime");
                    if ((nodeDateTime != null && Convert.ToBoolean(nodeDateTime.InnerText)) || nodeDateTime == null)
                    {
                        body += "<TR>";
                        body += "<TD>";
                        body += SysMsg.GetSystemMessage((SYS_LANGUAGE)(((object[])(clientInfo[0]))[0]), "FLRuntime", "InstanceManager", _dateTime);
                        body += "</TD>";
                        body += "<TD  COLSPAN=7>";
                        body += DateTime.Now.ToString();
                        body += "</TD>";
                        body += "</TR>";
                    }

                    XmlNode nodeHyperLink = doc.ChildNodes[0].SelectSingleNode("HyperLink");
                    if ((nodeHyperLink != null && Convert.ToBoolean(nodeHyperLink.InnerText)) || nodeHyperLink == null)
                    {
                        string webUrl = flInstance.GetWebUrl();
                        if (webUrl != null && webUrl != "0" && !string.IsNullOrEmpty(wfn))
                        {
                            List<object> objs = new List<object>();
                            string[] webFormNames = wfn.Split('.');
                            if (webFormNames.Length >= 2)
                            {
                                objs.Add(HttpUtility.UrlEncode(webFormNames[0]));
                                objs.Add(HttpUtility.UrlEncode(webFormNames[1]) + ".aspx");
                                objs.Add(HttpUtility.UrlEncode(flInstance.FLInstanceId.ToString()));
                                objs.Add(HttpUtility.UrlEncode((flInstance.CurrentFLActivity == null ? string.Empty : flInstance.CurrentFLActivity.Name) + ";" + nextFLActivity.Name));
                                objs.Add(HttpUtility.UrlEncode(keyValues[1].ToString()));
                                objs.Add(HttpUtility.UrlEncode(((int)nm).ToString()));
                                objs.Add(HttpUtility.UrlEncode(((int)fnm).ToString()));
                                objs.Add(HttpUtility.UrlEncode(users));
                                objs.Add(plusApprove);
                                objs.Add(plusApprove == 1 ? "A" : "");

                                if (webUrl != null && webUrl != string.Empty)
                                {
                                    webUrl = string.Format(webUrl, objs.ToArray());
                                }
                            }

                            body += "<TR>";
                            body += "<TD>";
                            body += SysMsg.GetSystemMessage((SYS_LANGUAGE)(((object[])(clientInfo[0]))[0]), "FLRuntime", "InstanceManager", _hyperLink);
                            body += "</TD>";
                            body += "<TD  COLSPAN=7>";
                            body += "<a href=" + webUrl + " target='_blank'>" + SysMsg.GetSystemMessage((SYS_LANGUAGE)(((object[])(clientInfo[0]))[0]), "FLRuntime", "InstanceManager", _hyperLink2) + "</a>";
                            body += "</TD>";
                            body += "</TR>";
                        }
                    }

                    XmlNode nodeComment = doc.ChildNodes[0].SelectSingleNode("Comment");
                    if ((nodeComment != null && Convert.ToBoolean(nodeComment.InnerText)) || nodeComment == null)
                    {
                        body += GetComments(flInstance.FLInstanceId.ToString(), clientInfo);
                    }

                    body += "</TABLE>";

                    //---------------------------------------------------------------

                    string subject = string.Empty;

                    XmlNode nodeFlowName2 = doc.ChildNodes[0].SelectSingleNode("FlowName2");
                    if ((nodeFlowName2 != null && Convert.ToBoolean(nodeFlowName2.InnerText)) || nodeFlowName2 == null)
                    {
                        subject += flowDesc + "-";
                    }

                    XmlNode nodeActivityName2 = doc.ChildNodes[0].SelectSingleNode("ActivityName2");
                    if ((nodeActivityName2 != null && Convert.ToBoolean(nodeActivityName2.InnerText)) || nodeActivityName2 == null)
                    {
                        subject += nextFLActivity.Name;
                    }

                    XmlNode nodeDescription2 = doc.ChildNodes[0].SelectSingleNode("Description2");
                    if ((nodeDescription2 != null && Convert.ToBoolean(nodeDescription2.InnerText)) || nodeDescription2 == null)
                    {
                        string remark = flInstance.FLFlag == 'X' ? "Reject(system)" : flInstanceParms[4].ToString();
                        //modified by lily 2009-5-11 審核信息有換行時會報錯
                        remark = remark.Replace("\r\n", " ");
                        if (subject.Length != 0)
                        {
                            subject += ",";
                        }

                        subject += remark;
                    }

                    XmlNode nodeSender2 = doc.ChildNodes[0].SelectSingleNode("Sender2");
                    if ((nodeSender2 != null && Convert.ToBoolean(nodeSender2.InnerText)) || nodeSender2 == null)
                    {
                        if (subject.Length != 0)
                        {
                            subject += ",";
                        }

                        subject += sUserId;
                        subject += "(" + sUserName + ")";
                    }

                    XmlNode nodeContent2 = doc.ChildNodes[0].SelectSingleNode("Content2");
                    if ((nodeContent2 != null && Convert.ToBoolean(nodeContent2.InnerText)) || nodeContent2 == null)
                    {
                        if (subject.Length != 0)
                        {
                            subject += ",";
                        }
                        if (string.IsNullOrEmpty(presenationCT))
                        {
                            string presentFields = ((IFLRootActivity)flInstance.RootFLActivity).PresentFields;
                            string keys = keyValues[0].ToString();
                            string presenation = keyValues[1].ToString();
                            presenationCT = Global.GetFormPresentCT(tableName, keys, presenation, presentFields, clientInfo);
                        }
                        subject += presenationCT;
                    }

                    if (subject.Length == 0 && body.Length == 0)
                    {
                        return;
                    }

                    SmtpClient client = new SmtpClient(smtp);
                    client.Timeout = 60000;
                    _client = client;

                    client.UseDefaultCredentials = true;
                    client.Credentials = new NetworkCredential(sendFrom, password);
                    client.DeliveryMethod = SmtpDeliveryMethod.Network;

                    MailMessage message = new MailMessage();
                    message.SubjectEncoding = Encoding.UTF8;
                    message.BodyEncoding = Encoding.UTF8;
                    message.From = new MailAddress(sendFrom, "Workflow", System.Text.Encoding.UTF8);
                    foreach (string sendTo in sendToes)
                    {
                        message.To.Add(new MailAddress(sendTo, sendTo, Encoding.UTF8));
                    }
                    message.IsBodyHtml = true;
                    message.Subject = subject;
                    message.Body = body;
                    _message = message;

                    Thread thread = new Thread(new ThreadStart(SendMail));
                    DateTime d1 = DateTime.Now;
                    thread.Start();
                    DateTime d2 = DateTime.Now;

                    //Console.Write("XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX:{0}", ((TimeSpan)(d2 - d1)).TotalMilliseconds);

                    //try
                    //{
                    //    //DateTime d1 = DateTime.Now;
                    //    //client.Send(message);
                    //    //DateTime d2 = DateTime.Now;

                    //    //Console.Write("XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX:{0}", ((TimeSpan)(d2 - d1)).TotalMilliseconds);
                    //}
                    //catch
                    //{

                    //}
                }
            }
        }

        /// <summary>
        /// 发送Email
        /// </summary>
        /// <param name="flInstance">流程</param>
        /// <param name="flInstanceParms">流程参数</param>
        /// <param name="keyValues">宿主筛选条件</param>
        /// <param name="roleId">角色Id</param>
        /// <param name="flActivity">Activity</param>
        /// <param name="clientInfo">ClientInfo</param>
        public static void SendTo2(FLInstance flInstance, object[] flInstanceParms, object[] keyValues, string roleId, FLActivity flActivity, object[] clientInfo)
        {
            string sendFrom = string.Empty;
            string password = string.Empty;
            string smtp = string.Empty;
            List<string> sendToes = new List<string>();

            string tableName = ((IFLRootActivity)flInstance.RootFLActivity).TableName;
            string flowDesc = ((IFLRootActivity)flInstance.RootFLActivity).Description;
            string sUserId = ((object[])clientInfo[0])[1].ToString();
            string sUserName = Global.GetUserName(sUserId, clientInfo);

            XmlDocument doc = new XmlDocument();
            if (File.Exists("Workflow.xml"))
                doc.Load("Workflow.xml");
            else
                return;

            bool active = false;
            XmlNode nodeActive = doc.ChildNodes[0].SelectSingleNode("Active");
            if (nodeActive != null)
            {
                active = Convert.ToBoolean(nodeActive.InnerText);
            }
            if (!active)
            {
                return;
            }


            XmlNode nodeEmail = doc.ChildNodes[0].SelectSingleNode("Email");
            if (nodeEmail != null)
            {
                sendFrom = nodeEmail.InnerText;
            }
            else
            {
                return;
            }

            XmlNode nodePassword = doc.ChildNodes[0].SelectSingleNode("Password");
            if (nodePassword != null)
            {
                password = GetPwdString(nodePassword.InnerText);
            }
            else
            {
                return;
            }

            XmlNode nodeSMTP = doc.ChildNodes[0].SelectSingleNode("SMTP");
            if (nodeSMTP != null)
            {
                smtp = nodeSMTP.InnerText;
            }
            else
            {
                return;
            }


            if (!(flActivity is IEventWaiting) && !(flActivity is IFLNotifyActivity))
            {
                return;
            }

            bool sm = false;
            if (flActivity is IEventWaiting)
            {
                sm = ((IEventWaiting)flActivity).SendEmail;
            }
            else if (flActivity is IFLNotifyActivity)
            {
                sm = ((IFLNotifyActivity)flActivity).SendEmail;
            }

            if (sm)
            {
                FLActivity nextFLActivity = flActivity;
                int plusApprove = 0;
                if (nextFLActivity is IFLStandActivity)
                {
                    plusApprove = Convert.ToInt32(((IFLStandActivity)nextFLActivity).PlusApprove);
                }
                else if (nextFLActivity is IFLApproveActivity)
                {
                    plusApprove = Convert.ToInt32(((IFLApproveActivity)nextFLActivity).PlusApprove);
                }
                else if (nextFLActivity is IFLApproveBranchActivity)
                {
                    FLActivity approve = flInstance.RootFLActivity.GetFLActivityByName(((IFLApproveBranchActivity)nextFLActivity).ParentActivity);
                    plusApprove = Convert.ToInt32(((IFLApproveActivity)approve).PlusApprove);
                }

                string users = string.Empty;
                string email = string.Empty;
                SendToKind sk = SendToKind.Applicate;
                string sr = string.Empty;
                string su = string.Empty;
                string sf = string.Empty;
                string fn = string.Empty;
                string wfn = string.Empty;
                NavigatorMode nm = NavigatorMode.Normal;
                FLNavigatorMode fnm = FLNavigatorMode.Notify;
                if (flActivity is IEventWaiting)
                {
                    sk = ((IEventWaiting)flActivity).SendToKind;
                    sr = ((IEventWaiting)flActivity).SendToRole;
                    su = ((IEventWaiting)flActivity).SendToUser;
                    sf = ((IEventWaiting)flActivity).SendToField;
                    wfn = string.IsNullOrEmpty(((IEventWaiting)flActivity).WebFormName)
                        ? ((IFLRootActivity)flInstance.RootFLActivity).WebFormName
                        : ((IEventWaiting)flActivity).WebFormName;
                    nm = ((IEventWaiting)flActivity).NavigatorMode;
                    fnm = ((IEventWaiting)flActivity).FLNavigatorMode;
                }
                else if (flActivity is IFLNotifyActivity)
                {
                    sk = ((IFLNotifyActivity)flActivity).SendToKind;
                    sr = ((IFLNotifyActivity)flActivity).SendToRole;
                    su = ((IFLNotifyActivity)flActivity).SendToUser;
                    sf = ((IFLNotifyActivity)flActivity).SendToField;
                    wfn = string.IsNullOrEmpty(((IFLNotifyActivity)flActivity).WebFormName)
                                 ? ((IFLRootActivity)flInstance.RootFLActivity).WebFormName
                                 : ((IFLNotifyActivity)flActivity).WebFormName;
                    nm = ((IFLNotifyActivity)flActivity).NavigatorMode;
                    fnm = ((IFLNotifyActivity)flActivity).FLNavigatorMode;
                }

                if (sk == SendToKind.Applicate)
                {
                    email = Global.GetUserEmail(flInstance.Creator, clientInfo);
                    if (email != null && email != string.Empty)
                        sendToes.Add(email);
                }
                else
                {
                    string orgKind = ((IFLRootActivity)flInstance.RootFLActivity).OrgKind;
                    if (sk == SendToKind.Role)
                    {
                        string q = sr;
                        string[] qq = q.Split(";".ToCharArray());

                        roleId = qq[0].Trim();
                    }
                    else if (sk == SendToKind.ApplicateManager)
                    {
                        List<string> roles = Global.GetRoleIdsByUserId(flInstance.Creator, clientInfo);
                        if (roles.Count > 0)
                        {
                            roleId = Global.GetManagerRoleId(roles[0], orgKind, clientInfo);
                        }
                    }
                    else if (sk == SendToKind.Manager)
                    {
                        if (flInstance.FLDirection == FLDirection.GoToBack)
                        {
                            roleId = ((IEventWaitingExecute)nextFLActivity).RoleId;
                        }
                        else
                        {
                            roleId = Global.GetManagerRoleId(flInstanceParms[5].ToString(), orgKind, clientInfo);
                        }
                    }
                    else if (sk == SendToKind.RefRole)
                    {
                        if (nextFLActivity is FLStandActivity && ((ISupportFLDetailsActivity)nextFLActivity).SendToId2 != string.Empty)
                        {
                            roleId = ((ISupportFLDetailsActivity)nextFLActivity).SendToId2;
                        }
                        else
                        {
                            roleId = Global.GetRoleIdByRefRole(sf, tableName, keyValues[1].ToString(), clientInfo);
                        }
                    }
                    else if (sk == SendToKind.RefManager)
                    {
                        if (flInstance.FLDirection == FLDirection.GoToBack)
                        {
                            roleId = ((IEventWaitingExecute)nextFLActivity).RoleId;
                        }
                        else
                        {
                            if (nextFLActivity is IFLApproveBranchActivity &&
                                ((FLApproveActivity)flInstance.RootFLActivity.GetFLActivityByName(((IFLApproveBranchActivity)nextFLActivity).ParentActivity)).I > 1)
                            {
                                roleId = Global.GetManagerRoleId(flInstanceParms[5].ToString(), orgKind, clientInfo);
                            }
                            else
                            {
                                string sendToField = sf;
                                string values = keyValues[1].ToString();

                                string s = Global.GetRoleIdByRefRole(sendToField, tableName, values, clientInfo);
                                roleId = Global.GetManagerRoleId(s.ToString(), orgKind, clientInfo);
                            }
                        }
                    }
                    else if (sk == SendToKind.RefUser)
                    {
                        string id = Global.GetRoleIdByRefRole(sf, tableName, keyValues[1].ToString(), clientInfo, true);

                        if (!string.IsNullOrEmpty(id))
                        {
                            string[] listusers = id.Split(';');
                            foreach (string user in listusers)
                            {
                                if (user.Trim().Length > 0)
                                {
                                    email = Global.GetUserEmail(user, clientInfo);
                                    if (email != null && email != string.Empty)
                                        sendToes.Add(email);
                                }
                            }
                        }
                    }
                    else if (sk == SendToKind.User)
                    {
                        string[] listusers = su.Split(';');
                        foreach (string user in listusers)
                        {
                            if (user.Trim().Length > 0)
                            {
                                email = Global.GetUserEmail(user, clientInfo);
                                if (email != null && email != string.Empty)
                                    sendToes.Add(email);
                            }
                        }
                    }
                    else
                    {
                        roleId = flInstanceParms[5].ToString();
                    }

                    List<string> userIds = new List<string>();
                    if (roleId != null && roleId != string.Empty)
                    {
                        userIds = Global.GetUsersIdsByRoleId(roleId, clientInfo);
                    }

                    foreach (string userId in userIds)
                    {
                        if (users.Length != 0)
                        {
                            users += ",";
                        }
                        users += userId;

                        email = Global.GetUserEmail(userId, clientInfo);
                        if (email != null && email != string.Empty)
                            sendToes.Add(email);
                    }
                }

                if (sendToes.Count == 0)
                {
                    return;
                }

                string body = string.Empty;
                body += "<TABLE BORDER=1>";

                XmlNode nodeSender = doc.ChildNodes[0].SelectSingleNode("Sender");
                if ((nodeSender != null && Convert.ToBoolean(nodeSender.InnerText)) || nodeSender == null)
                {
                    body += "<TR>";
                    body += "<TD WIDTH=150>";
                    body += SysMsg.GetSystemMessage((SYS_LANGUAGE)(((object[])(clientInfo[0]))[0]), "FLRuntime", "InstanceManager", _sender);
                    body += "</TD>";
                    body += "<TD  COLSPAN=7>";
                    body += string.Format("[{0}]{1}", sUserId, sUserName);
                    body += "</TD>";
                    body += "</TR>";
                }

                XmlNode nodeFlowName = doc.ChildNodes[0].SelectSingleNode("FlowName");
                if ((nodeFlowName != null && Convert.ToBoolean(nodeFlowName.InnerText)) || nodeFlowName == null)
                {
                    body += "<TR>";
                    body += "<TD>";
                    body += SysMsg.GetSystemMessage((SYS_LANGUAGE)(((object[])(clientInfo[0]))[0]), "FLRuntime", "InstanceManager", _flowName);
                    body += "</TD>";
                    body += "<TD  COLSPAN=7>";
                    body += string.IsNullOrEmpty(flowDesc) ? "&nbsp;" : flowDesc;
                    body += "</TD>";
                    body += "</TR>";
                }

                XmlNode nodeActivityName = doc.ChildNodes[0].SelectSingleNode("ActivityName");
                if ((nodeActivityName != null && Convert.ToBoolean(nodeActivityName.InnerText)) || nodeActivityName == null)
                {
                    body += "<TR>";
                    body += "<TD>";
                    body += SysMsg.GetSystemMessage((SYS_LANGUAGE)(((object[])(clientInfo[0]))[0]), "FLRuntime", "InstanceManager", _activityName);
                    body += "</TD>";
                    body += "<TD  COLSPAN=7>";
                    body += nextFLActivity.Name;
                    body += "</TD>";
                    body += "</TR>";
                }

                string presenationCT = null;
                XmlNode nodeContent = doc.ChildNodes[0].SelectSingleNode("Content");
                if ((nodeContent != null && Convert.ToBoolean(nodeContent.InnerText)) || nodeContent == null)
                {
                    string presentFields = ((IFLRootActivity)flInstance.RootFLActivity).PresentFields;
                    string keys = keyValues[0].ToString();
                    string presenation = keyValues[1].ToString();
                    presenationCT = Global.GetFormPresentCT(tableName, keys, presenation, presentFields, clientInfo);

                    body += GetPresentation(presenationCT);
                }

                XmlNode nodeDescription = doc.ChildNodes[0].SelectSingleNode("Description");
                if ((nodeDescription != null && Convert.ToBoolean(nodeDescription.InnerText)) || nodeDescription == null)
                {
                    string remark = flInstanceParms[4].ToString();
                    //意見內容有換行會報錯
                    remark = remark.Replace("\r\n", "<BR/>");
                    body += "<TR>";
                    body += "<TD>";
                    body += SysMsg.GetSystemMessage((SYS_LANGUAGE)(((object[])(clientInfo[0]))[0]), "FLRuntime", "InstanceManager", _description);
                    body += "</TD>";
                    body += "<TD  COLSPAN=7>";
                    body += string.IsNullOrEmpty(remark) ? "&nbsp;" : remark;
                    body += "</TD>";
                    body += "</TR>";
                }

                XmlNode nodeDateTime = doc.ChildNodes[0].SelectSingleNode("DateTime");
                if ((nodeDateTime != null && Convert.ToBoolean(nodeDateTime.InnerText)) || nodeDateTime == null)
                {
                    body += "<TR>";
                    body += "<TD>";
                    body += SysMsg.GetSystemMessage((SYS_LANGUAGE)(((object[])(clientInfo[0]))[0]), "FLRuntime", "InstanceManager", _dateTime);
                    body += "</TD>";
                    body += "<TD  COLSPAN=7>";
                    body += DateTime.Now.ToString();
                    body += "</TD>";
                    body += "</TR>";
                }

                XmlNode nodeHyperLink = doc.ChildNodes[0].SelectSingleNode("HyperLink");
                if ((nodeHyperLink != null && Convert.ToBoolean(nodeHyperLink.InnerText)) || nodeHyperLink == null)
                {
                    string webUrl = flInstance.GetWebUrl();
                    if (webUrl != null && webUrl != "0" && !string.IsNullOrEmpty(wfn))
                    {
                        List<object> objs = new List<object>();
                        string[] webFormNames = wfn.Split('.');
                        if (webFormNames.Length >= 2)
                        {
                            objs.Add(HttpUtility.UrlEncode(webFormNames[0]));
                            objs.Add(HttpUtility.UrlEncode(webFormNames[1]) + ".aspx");
                            objs.Add(HttpUtility.UrlEncode(flInstance.FLInstanceId.ToString()));
                            objs.Add(HttpUtility.UrlEncode((flInstance.CurrentFLActivity == null ? string.Empty : flInstance.CurrentFLActivity.Name) + ";" + nextFLActivity.Name));
                            objs.Add(HttpUtility.UrlEncode(keyValues[1].ToString()));
                            objs.Add(HttpUtility.UrlEncode(((int)nm).ToString()));
                            objs.Add(HttpUtility.UrlEncode(((int)fnm).ToString()));
                            objs.Add(HttpUtility.UrlEncode(users));
                            objs.Add(plusApprove);
                            objs.Add(plusApprove == 1 ? "A" : "");

                            if (webUrl != null && webUrl != string.Empty)
                            {
                                webUrl = string.Format(webUrl, objs.ToArray());
                            }
                        }

                        body += "<TR>";
                        body += "<TD>";
                        body += SysMsg.GetSystemMessage((SYS_LANGUAGE)(((object[])(clientInfo[0]))[0]), "FLRuntime", "InstanceManager", _hyperLink);
                        body += "</TD>";
                        body += "<TD  COLSPAN=7>";
                        body += "<a href=" + webUrl + " target='_blank'>" + SysMsg.GetSystemMessage((SYS_LANGUAGE)(((object[])(clientInfo[0]))[0]), "FLRuntime", "InstanceManager", _hyperLink2) + "</a>";
                        body += "</TD>";
                        body += "</TR>";
                    }
                }

                XmlNode nodeComment = doc.ChildNodes[0].SelectSingleNode("Comment");
                if ((nodeComment != null && Convert.ToBoolean(nodeComment.InnerText)) || nodeComment == null)
                {
                    body += GetComments(flInstance.FLInstanceId.ToString(), clientInfo);
                }

                body += "</TABLE>";

                //---------------------------------------------------------------

                string subject = SysMsg.GetSystemMessage((SYS_LANGUAGE)(((object[])(clientInfo[0]))[0]), "FLRuntime", "InstanceManager", _overTime);

                XmlNode nodeFlowName2 = doc.ChildNodes[0].SelectSingleNode("FlowName2");
                if ((nodeFlowName2 != null && Convert.ToBoolean(nodeFlowName2.InnerText)) || nodeFlowName2 == null)
                {
                    subject += flowDesc + "-";
                }

                XmlNode nodeActivityName2 = doc.ChildNodes[0].SelectSingleNode("ActivityName2");
                if ((nodeActivityName2 != null && Convert.ToBoolean(nodeActivityName2.InnerText)) || nodeActivityName2 == null)
                {
                    subject += nextFLActivity.Name;
                }

                XmlNode nodeDescription2 = doc.ChildNodes[0].SelectSingleNode("Description2");
                if ((nodeDescription2 != null && Convert.ToBoolean(nodeDescription2.InnerText)) || nodeDescription2 == null)
                {
                    string remark = flInstanceParms[4].ToString();
                    //意見內容有換行會報錯
                    remark = remark.Replace("\r\n", " ");
                    if (subject.Length != 0)
                    {
                        subject += ",";
                    }

                    subject += remark;
                }

                XmlNode nodeSender2 = doc.ChildNodes[0].SelectSingleNode("Sender2");
                if ((nodeSender2 != null && Convert.ToBoolean(nodeSender2.InnerText)) || nodeSender2 == null)
                {
                    if (subject.Length != 0)
                    {
                        subject += ",";
                    }

                    subject += sUserId;
                    subject += "(" + sUserName + ")";
                }

                XmlNode nodeContent2 = doc.ChildNodes[0].SelectSingleNode("Content2");
                if ((nodeContent2 != null && Convert.ToBoolean(nodeContent2.InnerText)) || nodeContent2 == null)
                {
                    if (subject.Length != 0)
                    {
                        subject += ",";
                    }
                    if (string.IsNullOrEmpty(presenationCT))
                    {
                        string presentFields = ((IFLRootActivity)flInstance.RootFLActivity).PresentFields;
                        string keys = keyValues[0].ToString();
                        string presenation = keyValues[1].ToString();
                        presenationCT = Global.GetFormPresentCT(tableName, keys, presenation, presentFields, clientInfo);
                    }
                    subject += presenationCT;
                }

                if (subject.Length == 0 && body.Length == 0)
                {
                    return;
                }

                SmtpClient client = new SmtpClient(smtp);
                client.Timeout = 60000;
                _client = client;

                client.UseDefaultCredentials = true;
                client.Credentials = new NetworkCredential(sendFrom, password);
                client.DeliveryMethod = SmtpDeliveryMethod.Network;

                MailMessage message = new MailMessage();
                message.SubjectEncoding = Encoding.UTF8;
                message.Priority = MailPriority.High;
                message.BodyEncoding = Encoding.UTF8;
                message.From = new MailAddress(sendFrom, "Workflow", System.Text.Encoding.UTF8);
                foreach (string sendTo in sendToes)
                {
                    message.To.Add(new MailAddress(sendTo, sendTo, Encoding.UTF8));
                }
                message.IsBodyHtml = true;
                message.Subject = subject;
                message.Body = body;
                _message = message;

                Thread thread = new Thread(new ThreadStart(SendMail));
                DateTime d1 = DateTime.Now;
                thread.Start();
                DateTime d2 = DateTime.Now;
            }
        }

        /// <summary>
        /// 发送Email
        /// </summary>
        /// <param name="flInstance">流程</param>
        /// <param name="flInstanceParms">流程参数</param>
        /// <param name="keyValues">宿主筛选条件</param>
        /// <param name="roleId">角色Id</param>
        /// <param name="flActivity">Activity</param>
        /// <param name="clientInfo">ClientInfo</param>
        public static void SendTo3(FLInstance flInstance, object[] flInstanceParms, object[] keyValues, FLActivity flActivity, object[] clientInfo)
        {
            string body = string.Empty;
            string sendFrom = string.Empty;
            string password = string.Empty;
            string smtp = string.Empty;
            List<string> sendToes = new List<string>();

            string tableName = ((IFLRootActivity)flInstance.RootFLActivity).TableName;
            string flowDesc = ((IFLRootActivity)flInstance.RootFLActivity).Description;
            string sUserId = ((object[])clientInfo[0])[1].ToString();
            string sUserName = Global.GetUserName(sUserId, clientInfo);

            XmlDocument doc = new XmlDocument();
            if (File.Exists("Workflow.xml"))
                doc.Load("Workflow.xml");
            else
                return;

            bool active = false;
            XmlNode nodeActive = doc.ChildNodes[0].SelectSingleNode("Active");
            if (nodeActive != null)
            {
                active = Convert.ToBoolean(nodeActive.InnerText);
            }
            if (!active)
            {
                return;
            }

            XmlNode nodeEmail = doc.ChildNodes[0].SelectSingleNode("Email");
            if (nodeEmail != null)
            {
                sendFrom = nodeEmail.InnerText;
            }
            else
            {
                return;
            }

            XmlNode nodePassword = doc.ChildNodes[0].SelectSingleNode("Password");
            if (nodePassword != null)
            {
                password = GetPwdString(nodePassword.InnerText);
            }
            else
            {
                return;
            }

            XmlNode nodeSMTP = doc.ChildNodes[0].SelectSingleNode("SMTP");
            if (nodeSMTP != null)
            {
                smtp = nodeSMTP.InnerText;
            }
            else
            {
                return;
            }

            FLActivity nextFLActivity = flActivity;
            int plusApprove = 0;
            if (nextFLActivity is IFLStandActivity)
            {
                plusApprove = Convert.ToInt32(((IFLStandActivity)nextFLActivity).PlusApprove);
            }
            else if (nextFLActivity is IFLApproveActivity)
            {
                plusApprove = Convert.ToInt32(((IFLApproveActivity)nextFLActivity).PlusApprove);
            }
            else if (nextFLActivity is IFLApproveBranchActivity)
            {
                FLActivity approve = flInstance.RootFLActivity.GetFLActivityByName(((IFLApproveBranchActivity)nextFLActivity).ParentActivity);
                plusApprove = Convert.ToInt32(((IFLApproveActivity)approve).PlusApprove);
            }

            string users = string.Empty;
            string email = string.Empty;
            SendToKind sk = SendToKind.Applicate;
            string sr = string.Empty;
            string sf = string.Empty;
            string fn = string.Empty;
            string wfn = string.Empty;
            NavigatorMode nm = NavigatorMode.Normal;
            FLNavigatorMode fnm = FLNavigatorMode.Notify;
            if (flActivity is IEventWaiting)
            {
                sk = ((IEventWaiting)flActivity).SendToKind;
                sr = ((IEventWaiting)flActivity).SendToRole;
                sf = ((IEventWaiting)flActivity).SendToField;
                wfn = string.IsNullOrEmpty(((IEventWaiting)flActivity).WebFormName)
                    ? ((IFLRootActivity)flInstance.RootFLActivity).WebFormName
                    : ((IEventWaiting)flActivity).WebFormName;
                nm = ((IEventWaiting)flActivity).NavigatorMode;
                fnm = ((IEventWaiting)flActivity).FLNavigatorMode;
            }
            else if (flActivity is IFLNotifyActivity)
            {
                sk = ((IFLNotifyActivity)flActivity).SendToKind;
                sr = ((IFLNotifyActivity)flActivity).SendToRole;
                sf = ((IFLNotifyActivity)flActivity).SendToField;
                wfn = string.IsNullOrEmpty(((IFLNotifyActivity)flActivity).WebFormName)
                             ? ((IFLRootActivity)flInstance.RootFLActivity).WebFormName
                             : ((IFLNotifyActivity)flActivity).WebFormName;
                nm = ((IFLNotifyActivity)flActivity).NavigatorMode;
                fnm = ((IFLNotifyActivity)flActivity).FLNavigatorMode;
            }

            List<string> userIds = new List<string>();

            string s = flInstanceParms[8].ToString();
            string[] ss = s.Split(';');
            foreach (string id in ss)
            {
                if (string.IsNullOrEmpty(id))
                    continue;

                string[] ss1 = id.Split(':');
                if (ss1.Length <= 1)
                {
                    userIds.AddRange(Global.GetUsersIdsByRoleId(ss1[0], clientInfo));
                }
                else
                {
                    userIds.Add(ss1[0]);
                }
            }

            foreach (string userId in userIds)
            {
                if (users.Length != 0)
                {
                    users += ",";
                }
                users += userId;

                email = Global.GetUserEmail(userId, clientInfo);
                if (email != null && email != string.Empty)
                    sendToes.Add(email);
            }

            if (sendToes.Count == 0)
            {
                return;
            }

            body += "<TABLE BORDER=1>";

            XmlNode nodeSender = doc.ChildNodes[0].SelectSingleNode("Sender");
            if ((nodeSender != null && Convert.ToBoolean(nodeSender.InnerText)) || nodeSender == null)
            {
                body += "<TR>";
                body += "<TD WIDTH=150>";
                body += SysMsg.GetSystemMessage((SYS_LANGUAGE)(((object[])(clientInfo[0]))[0]), "FLRuntime", "InstanceManager", _sender);
                body += "</TD>";
                body += "<TD  COLSPAN=7>";
                body += string.Format("[{0}]{1}", sUserId, sUserName);
                body += "</TD>";
                body += "</TR>";
            }

            XmlNode nodeFlowName = doc.ChildNodes[0].SelectSingleNode("FlowName");
            if ((nodeFlowName != null && Convert.ToBoolean(nodeFlowName.InnerText)) || nodeFlowName == null)
            {
                body += "<TR>";
                body += "<TD>";
                body += SysMsg.GetSystemMessage((SYS_LANGUAGE)(((object[])(clientInfo[0]))[0]), "FLRuntime", "InstanceManager", _flowName);
                body += "</TD>";
                body += "<TD  COLSPAN=7>";
                body += string.IsNullOrEmpty(flowDesc) ? "&nbsp;" : flowDesc;
                body += "</TD>";
                body += "</TR>";
            }

            XmlNode nodeActivityName = doc.ChildNodes[0].SelectSingleNode("ActivityName");
            if ((nodeActivityName != null && Convert.ToBoolean(nodeActivityName.InnerText)) || nodeActivityName == null)
            {
                body += "<TR>";
                body += "<TD>";
                body += SysMsg.GetSystemMessage((SYS_LANGUAGE)(((object[])(clientInfo[0]))[0]), "FLRuntime", "InstanceManager", _activityName);
                body += "</TD>";
                body += "<TD  COLSPAN=7>";
                body += nextFLActivity.Name;
                body += "</TD>";
                body += "</TR>";
            }

            string presenationCT = null;
            XmlNode nodeContent = doc.ChildNodes[0].SelectSingleNode("Content");
            if ((nodeContent != null && Convert.ToBoolean(nodeContent.InnerText)) || nodeContent == null)
            {
                string presentFields = ((IFLRootActivity)flInstance.RootFLActivity).PresentFields;
                string keys = keyValues[0].ToString();
                string presenation = keyValues[1].ToString();
                presenationCT = Global.GetFormPresentCT(tableName, keys, presenation, presentFields, clientInfo);

                body += GetPresentation(presenationCT);
            }

            XmlNode nodeDescription = doc.ChildNodes[0].SelectSingleNode("Description");
            if ((nodeDescription != null && Convert.ToBoolean(nodeDescription.InnerText)) || nodeDescription == null)
            {
                string remark = flInstance.IsReturn == true ? "Return(system)" : (flInstanceParms[4] == null ? string.Empty : flInstanceParms[4].ToString());
                //意見內容有換行會報錯
                remark = remark.Replace("\r\n", "<BR/>");
                body += "<TR>";
                body += "<TD>";
                body += SysMsg.GetSystemMessage((SYS_LANGUAGE)(((object[])(clientInfo[0]))[0]), "FLRuntime", "InstanceManager", _description);
                body += "</TD>";
                body += "<TD  COLSPAN=7>";
                body += string.IsNullOrEmpty(remark) ? "&nbsp;" : remark;
                body += "</TD>";
                body += "</TR>";
            }

            XmlNode nodeDateTime = doc.ChildNodes[0].SelectSingleNode("DateTime");
            if ((nodeDateTime != null && Convert.ToBoolean(nodeDateTime.InnerText)) || nodeDateTime == null)
            {
                body += "<TR>";
                body += "<TD>";
                body += SysMsg.GetSystemMessage((SYS_LANGUAGE)(((object[])(clientInfo[0]))[0]), "FLRuntime", "InstanceManager", _dateTime);
                body += "</TD>";
                body += "<TD  COLSPAN=7>";
                body += DateTime.Now.ToString();
                body += "</TD>";
                body += "</TR>";
            }

            XmlNode nodeHyperLink = doc.ChildNodes[0].SelectSingleNode("HyperLink");
            if ((nodeHyperLink != null && Convert.ToBoolean(nodeHyperLink.InnerText)) || nodeHyperLink == null)
            {
                string webUrl = flInstance.GetWebUrl();
                if (webUrl != null && webUrl != "0" && !string.IsNullOrEmpty(wfn))
                {
                    List<object> objs = new List<object>();
                    string[] webFormNames = wfn.Split('.');
                    if (webFormNames.Length >= 2)
                    {
                        objs.Add(HttpUtility.UrlEncode(webFormNames[0]));
                        objs.Add(HttpUtility.UrlEncode(webFormNames[1]) + ".aspx");
                        objs.Add(HttpUtility.UrlEncode(flInstance.FLInstanceId.ToString()));
                        objs.Add(HttpUtility.UrlEncode((flInstance.CurrentFLActivity == null ? string.Empty : flInstance.CurrentFLActivity.Name) + ";" + nextFLActivity.Name));
                        objs.Add(HttpUtility.UrlEncode(keyValues[1].ToString()));
                        objs.Add(HttpUtility.UrlEncode(((int)nm).ToString()));
                        objs.Add(HttpUtility.UrlEncode(((int)fnm).ToString()));
                        objs.Add(HttpUtility.UrlEncode(users));
                        objs.Add(plusApprove);
                        objs.Add(plusApprove == 1 ? "A" : "");

                        if (webUrl != null && webUrl != string.Empty)
                        {
                            webUrl = string.Format(webUrl, objs.ToArray());
                        }
                    }

                    body += "<TR>";
                    body += "<TD>";
                    body += SysMsg.GetSystemMessage((SYS_LANGUAGE)(((object[])(clientInfo[0]))[0]), "FLRuntime", "InstanceManager", _hyperLink);
                    body += "</TD>";
                    body += "<TD  COLSPAN=7>";
                    body += "<a href=" + webUrl + " target='_blank'>" + SysMsg.GetSystemMessage((SYS_LANGUAGE)(((object[])(clientInfo[0]))[0]), "FLRuntime", "InstanceManager", _hyperLink2) + "</a>";
                    body += "</TD>";
                    body += "</TR>";
                }
            }

            XmlNode nodeComment = doc.ChildNodes[0].SelectSingleNode("Comment");
            if ((nodeComment != null && Convert.ToBoolean(nodeComment.InnerText)) || nodeComment == null)
            {
                body += GetComments(flInstance.FLInstanceId.ToString(), clientInfo);
            }

            body += "</TABLE>";

            //---------------------------------------------------------------

            string subject = string.Empty;
            XmlNode nodeFlowName2 = doc.ChildNodes[0].SelectSingleNode("FlowName2");
            if ((nodeFlowName2 != null && Convert.ToBoolean(nodeFlowName2.InnerText)) || nodeFlowName2 == null)
            {
                subject += flowDesc + "-";
            }

            XmlNode nodeActivityName2 = doc.ChildNodes[0].SelectSingleNode("ActivityName2");
            if ((nodeActivityName2 != null && Convert.ToBoolean(nodeActivityName2.InnerText)) || nodeActivityName2 == null)
            {
                subject += nextFLActivity.Name;
            }

            XmlNode nodeDescription2 = doc.ChildNodes[0].SelectSingleNode("Description2");
            if ((nodeDescription2 != null && Convert.ToBoolean(nodeDescription2.InnerText)) || nodeDescription2 == null)
            {
                string remark = "";
                if (subject.Length != 0)
                {
                    subject += ",";
                }

                subject += remark;
            }

            XmlNode nodeSender2 = doc.ChildNodes[0].SelectSingleNode("Sender2");
            if ((nodeSender2 != null && Convert.ToBoolean(nodeSender2.InnerText)) || nodeSender2 == null)
            {
                if (subject.Length != 0)
                {
                    subject += ",";
                }

                subject += sUserId;
                subject += "(" + sUserName + ")";
            }

            XmlNode nodeContent2 = doc.ChildNodes[0].SelectSingleNode("Content2");
            if ((nodeContent2 != null && Convert.ToBoolean(nodeContent2.InnerText)) || nodeContent2 == null)
            {
                if (subject.Length != 0)
                {
                    subject += ",";
                }
                if (string.IsNullOrEmpty(presenationCT))
                {
                    string presentFields = ((IFLRootActivity)flInstance.RootFLActivity).PresentFields;
                    string keys = keyValues[0].ToString();
                    string presenation = keyValues[1].ToString();
                    presenationCT = Global.GetFormPresentCT(tableName, keys, presenation, presentFields, clientInfo);
                }
                subject += presenationCT;
            }


            if (subject.Length == 0 && body.Length == 0)
            {
                return;
            }

            SmtpClient client = new SmtpClient(smtp);
            client.Timeout = 60000;
            _client = client;

            client.UseDefaultCredentials = true;
            client.Credentials = new NetworkCredential(sendFrom, password);
            client.DeliveryMethod = SmtpDeliveryMethod.Network;

            MailMessage message = new MailMessage();
            message.SubjectEncoding = Encoding.UTF8;
            message.BodyEncoding = Encoding.UTF8;
            message.From = new MailAddress(sendFrom, "Workflow", System.Text.Encoding.UTF8);
            foreach (string sendTo in sendToes)
            {
                message.To.Add(new MailAddress(sendTo, sendTo, Encoding.UTF8));
            }
            message.IsBodyHtml = true;
            message.Subject = subject;
            message.Body = body;
            _message = message;

            Thread thread = new Thread(new ThreadStart(SendMail));
            DateTime d1 = DateTime.Now;
            thread.Start();
            DateTime d2 = DateTime.Now;
        }

        /// <summary>
        /// 发送Email
        /// </summary>
        /// <param name="flInstance">流程</param>
        /// <param name="flInstanceParms">流程参数</param>
        /// <param name="keyValues">宿主筛选条件</param>
        /// <param name="clientInfo">ClientInfo</param>
        public static void SendTo4(FLInstance flInstance, object[] flInstanceParms, object[] keyValues, object[] clientInfo)
        {
            string sendFrom = string.Empty;
            string password = string.Empty;
            string smtp = string.Empty;
            List<string> sendToes = new List<string>();

            List<FLActivity> nextFLActivities = flInstance.NextFLActivities;
            List<string> tmpList = new List<string>();
            foreach (FLActivity flActivity in nextFLActivities)
            {
                if (flActivity is IEventWaiting)
                {
                    IEventWaiting nextFLActivity = (IEventWaiting)flActivity;
                    tmpList.Add(nextFLActivity.Name);
                }
                else if (flActivity is IFLNotifyActivity)
                {
                    IFLNotifyActivity nextFLActivity = (IFLNotifyActivity)flActivity;
                    tmpList.Add(nextFLActivity.Name);
                }
            }
            if (tmpList.Count == 0)
                return;

            string tableName = ((IFLRootActivity)flInstance.RootFLActivity).TableName;
            string flowDesc = ((IFLRootActivity)flInstance.RootFLActivity).Description;
            string sUserId = ((object[])clientInfo[0])[1].ToString();
            string sUserName = Global.GetUserName(sUserId, clientInfo);

            XmlDocument doc = new XmlDocument();
            if (File.Exists("Workflow.xml"))
                doc.Load("Workflow.xml");
            else
                return;

            bool active = false;
            XmlNode nodeActive = doc.ChildNodes[0].SelectSingleNode("Active");
            if (nodeActive != null)
            {
                active = Convert.ToBoolean(nodeActive.InnerText);
            }
            if (!active)
            {
                return;
            }


            XmlNode nodeEmail = doc.ChildNodes[0].SelectSingleNode("Email");
            if (nodeEmail != null)
            {
                sendFrom = nodeEmail.InnerText;
            }
            else
            {
                return;
            }

            XmlNode nodePassword = doc.ChildNodes[0].SelectSingleNode("Password");
            if (nodePassword != null)
            {
                password = GetPwdString(nodePassword.InnerText);
            }
            else
            {
                return;
            }

            XmlNode nodeSMTP = doc.ChildNodes[0].SelectSingleNode("SMTP");
            if (nodeSMTP != null)
            {
                smtp = nodeSMTP.InnerText;
            }
            else
            {
                return;
            }

            foreach (FLActivity flActivity in nextFLActivities)
            {
                string body = string.Empty;
                sendToes.Clear();
                if (!(flActivity is IEventWaiting) && !(flActivity is IFLNotifyActivity))
                {
                    continue;
                }

                FLActivity nextFLActivity = flActivity;
                int plusApprove = 0;
                if (nextFLActivity is IFLStandActivity)
                {
                    plusApprove = Convert.ToInt32(((IFLStandActivity)nextFLActivity).PlusApprove);
                }
                else if (nextFLActivity is IFLApproveActivity)
                {
                    plusApprove = Convert.ToInt32(((IFLApproveActivity)nextFLActivity).PlusApprove);
                }
                else if (nextFLActivity is IFLApproveBranchActivity)
                {
                    FLActivity approve = flInstance.RootFLActivity.GetFLActivityByName(((IFLApproveBranchActivity)nextFLActivity).ParentActivity);
                    plusApprove = Convert.ToInt32(((IFLApproveActivity)approve).PlusApprove);
                }

                string users = string.Empty;
                string email = string.Empty;
                SendToKind sk = SendToKind.Applicate;
                string sr = string.Empty;
                string su = string.Empty;
                string sf = string.Empty;
                string fn = string.Empty;
                string wfn = string.Empty;
                NavigatorMode nm = NavigatorMode.Normal;
                FLNavigatorMode fnm = FLNavigatorMode.Notify;
                if (flActivity is IEventWaiting)
                {
                    sk = ((IEventWaiting)flActivity).SendToKind;
                    sr = ((IEventWaiting)flActivity).SendToRole;
                    su = ((IEventWaiting)flActivity).SendToUser;
                    sf = ((IEventWaiting)flActivity).SendToField;
                    wfn = string.IsNullOrEmpty(((IEventWaiting)flActivity).WebFormName)
                        ? ((IFLRootActivity)flInstance.RootFLActivity).WebFormName
                        : ((IEventWaiting)flActivity).WebFormName;
                    nm = ((IEventWaiting)flActivity).NavigatorMode;
                    fnm = ((IEventWaiting)flActivity).FLNavigatorMode;
                }
                else if (flActivity is IFLNotifyActivity)
                {
                    sk = ((IFLNotifyActivity)flActivity).SendToKind;
                    sr = ((IFLNotifyActivity)flActivity).SendToRole;
                    su = ((IFLNotifyActivity)flActivity).SendToUser;
                    sf = ((IFLNotifyActivity)flActivity).SendToField;
                    wfn = string.IsNullOrEmpty(((IFLNotifyActivity)flActivity).WebFormName)
                                 ? ((IFLRootActivity)flInstance.RootFLActivity).WebFormName
                                 : ((IFLNotifyActivity)flActivity).WebFormName;
                    nm = ((IFLNotifyActivity)flActivity).NavigatorMode;
                    fnm = ((IFLNotifyActivity)flActivity).FLNavigatorMode;
                }

                if (sk == SendToKind.Applicate)
                {
                    email = Global.GetUserEmail(flInstance.Creator, clientInfo);
                    if (email != null && email != string.Empty)
                        sendToes.Add(email);
                }
                else
                {
                    List<string> roleIds = new List<string>();
                    // string roleId = string.Empty;
                    string orgKind = ((IFLRootActivity)flInstance.RootFLActivity).OrgKind;
                    if (flInstance.IsPlusApprove)
                    {
                        string q = flInstanceParms[8].ToString();
                        string[] qq = q.Split(";".ToCharArray());
                        foreach (string r in qq)
                        {
                            if (!string.IsNullOrEmpty(r))
                            {
                                roleIds.Add(r);
                            }
                        }
                    }
                    else
                    {
                        if (sk == SendToKind.Role)
                        {
                            string q = sr;
                            string[] qq = q.Split(";".ToCharArray());

                            // roleId = qq[0].Trim();
                            roleIds.Add(qq[0].Trim());
                        }
                        else if (sk == SendToKind.ApplicateManager)
                        {
                            List<string> roles = Global.GetRoleIdsByUserId(flInstance.Creator, clientInfo);
                            if (roles.Count > 0)
                            {
                                roleIds.Add( Global.GetManagerRoleId(roles[0], orgKind, clientInfo));
                            }
                        }
                        else if (sk == SendToKind.Manager)
                        {
                            if (flInstance.FLDirection == FLDirection.GoToBack)
                            {
                                // roleId = ((IEventWaitingExecute)nextFLActivity).RoleId;
                                roleIds.Add(((IEventWaitingExecute)nextFLActivity).RoleId);
                            }
                            else
                            {
                                // roleId = Global.GetManagerRoleId(flInstanceParms[5].ToString(), orgKind, clientInfo);
                                roleIds.Add(Global.GetManagerRoleId(flInstanceParms[5].ToString(), orgKind, clientInfo));
                            }
                        }
                        else if (sk == SendToKind.RefRole)
                        {
                            if (nextFLActivity is FLStandActivity && ((ISupportFLDetailsActivity)nextFLActivity).SendToId2 != string.Empty)
                            {
                                // roleId = ((ISupportFLDetailsActivity)nextFLActivity).SendToId2;
                                roleIds.Add(((ISupportFLDetailsActivity)nextFLActivity).SendToId2);
                            }
                            else
                            {
                                // roleId = Global.GetRoleIdByRefRole(sf, tableName, keyValues[1].ToString(), clientInfo);
                                roleIds.Add(Global.GetRoleIdByRefRole(sf, tableName, keyValues[1].ToString(), clientInfo));
                            }
                        }
                        else if (sk == SendToKind.RefManager)
                        {
                            if (flInstance.FLDirection == FLDirection.GoToBack)
                            {
                                // roleId = ((IEventWaitingExecute)nextFLActivity).RoleId;
                                roleIds.Add(((IEventWaitingExecute)nextFLActivity).RoleId);
                            }
                            else
                            {
                                if (nextFLActivity is IFLApproveBranchActivity &&
                                    ((FLApproveActivity)flInstance.RootFLActivity.GetFLActivityByName(((IFLApproveBranchActivity)nextFLActivity).ParentActivity)).I > 1)
                                {
                                    // roleId = Global.GetManagerRoleId(flInstanceParms[5].ToString(), orgKind, clientInfo);
                                    roleIds.Add(Global.GetManagerRoleId(flInstanceParms[5].ToString(), orgKind, clientInfo));
                                }
                                else
                                {
                                    string sendToField = sf;
                                    string values = keyValues[1].ToString();

                                    string s = Global.GetRoleIdByRefRole(sendToField, tableName, values, clientInfo);
                                    // roleId = Global.GetManagerRoleId(s.ToString(), orgKind, clientInfo);
                                    roleIds.Add(Global.GetManagerRoleId(s.ToString(), orgKind, clientInfo));
                                }
                            }
                        }
                        else if (sk == SendToKind.RefUser)
                        {
                            string id = Global.GetRoleIdByRefRole(sf, tableName, keyValues[1].ToString(), clientInfo, true);

                            if (!string.IsNullOrEmpty(id))
                            {
                                string[] listusers = id.Split(';');
                                foreach (string user in listusers)
                                {
                                    if (user.Trim().Length > 0)
                                    {
                                        email = Global.GetUserEmail(user, clientInfo);
                                        if (email != null && email != string.Empty)
                                            sendToes.Add(email);
                                    }
                                }
                            }
                        }
                        else if (sk == SendToKind.User)
                        {
                            string[] listusers = su.Split(';');
                            foreach (string user in listusers)
                            {
                                if (user.Trim().Length > 0)
                                {
                                    email = Global.GetUserEmail(user, clientInfo);
                                    if (email != null && email != string.Empty)
                                        sendToes.Add(email);
                                }
                            }
                        }


                        else if (flActivity is IFLNotifyActivity & sk == SendToKind.AllRoles)
                        {
                            foreach (string r in flInstance.RL)
                            {
                                if (string.IsNullOrEmpty(r))
                                    continue;

                                string[] rr = r.Split(":".ToCharArray());
                                if (rr[0] == "R")
                                {
                                    roleIds.Add(rr[1]);
                                }
                                else
                                {
                                    roleIds.Add(r);
                                }

                                roleIds.Add(string.Format("U:{0}", flInstance.Creator));
                            }
                        }
                        else
                        {
                            // roleId = flInstanceParms[5].ToString();
                            roleIds.Add(flInstanceParms[5].ToString());
                        }
                    }

                    List<string> userIds = new List<string>();
                    //if (roleId != null && roleId != string.Empty)
                    //{
                    //    userIds = Global.GetUsersIdsByRoleId(roleId, clientInfo);
                    //}
                    List<string> tempIds = new List<string>();
                    foreach (string r in roleIds)
                    {
                        string[] rr = r.Split(":".ToCharArray());
                        if (rr.Length > 1)
                        {
                            tempIds.Add(rr[1]);
                        }

                        tempIds.AddRange(Global.GetUsersIdsByRoleId(r, clientInfo));
                    }
                    foreach (string u in tempIds)
                    {
                        if (userIds.Contains(u))
                            continue;

                        userIds.Add(u);
                    }

                    foreach (string userId in userIds)
                    {
                        if (users.Length != 0)
                        {
                            users += ",";
                        }
                        users += userId;

                        email = Global.GetUserEmail(userId, clientInfo);
                        if (email != null && email != string.Empty)
                            sendToes.Add(email);
                    }
                }

                if (sendToes.Count == 0)
                {
                    continue;
                }

                body += "<TABLE BORDER=1>";

                XmlNode nodeSender = doc.ChildNodes[0].SelectSingleNode("Sender");
                if ((nodeSender != null && Convert.ToBoolean(nodeSender.InnerText)) || nodeSender == null)
                {
                    body += "<TR>";
                    body += "<TD WIDTH=150>";
                    body += SysMsg.GetSystemMessage((SYS_LANGUAGE)(((object[])(clientInfo[0]))[0]), "FLRuntime", "InstanceManager", _sender);
                    body += "</TD>";
                    body += "<TD  COLSPAN=7>";
                    body += string.Format("[{0}]{1}", sUserId, sUserName);
                    body += "</TD>";
                    body += "</TR>";
                }

                XmlNode nodeFlowName = doc.ChildNodes[0].SelectSingleNode("FlowName");
                if ((nodeFlowName != null && Convert.ToBoolean(nodeFlowName.InnerText)) || nodeFlowName == null)
                {
                    body += "<TR>";
                    body += "<TD>";
                    body += SysMsg.GetSystemMessage((SYS_LANGUAGE)(((object[])(clientInfo[0]))[0]), "FLRuntime", "InstanceManager", _flowName);
                    body += "</TD>";
                    body += "<TD  COLSPAN=7>";
                    body += string.IsNullOrEmpty(flowDesc) ? "&nbsp;" : flowDesc;
                    body += "</TD>";
                    body += "</TR>";
                }

                XmlNode nodeActivityName = doc.ChildNodes[0].SelectSingleNode("ActivityName");
                if ((nodeActivityName != null && Convert.ToBoolean(nodeActivityName.InnerText)) || nodeActivityName == null)
                {
                    body += "<TR>";
                    body += "<TD>";
                    body += SysMsg.GetSystemMessage((SYS_LANGUAGE)(((object[])(clientInfo[0]))[0]), "FLRuntime", "InstanceManager", _activityName);
                    body += "</TD>";
                    body += "<TD  COLSPAN=7>";
                    body += nextFLActivity.Name;
                    body += "</TD>";
                    body += "</TR>";
                }

                string presenationCT = null;
                XmlNode nodeContent = doc.ChildNodes[0].SelectSingleNode("Content");
                if ((nodeContent != null && Convert.ToBoolean(nodeContent.InnerText)) || nodeContent == null)
                {
                    string presentFields = ((IFLRootActivity)flInstance.RootFLActivity).PresentFields;
                    string keys = keyValues[0].ToString();
                    string presenation = keyValues[1].ToString();
                    presenationCT = Global.GetFormPresentCT(tableName, keys, presenation, presentFields, clientInfo);

                    body += GetPresentation(presenationCT);
                }

                XmlNode nodeDescription = doc.ChildNodes[0].SelectSingleNode("Description");
                if ((nodeDescription != null && Convert.ToBoolean(nodeDescription.InnerText)) || nodeDescription == null)
                {
                    string remark = flInstance.FLFlag == 'X' ? "Reject(system)" : flInstanceParms[4].ToString();
                    //意見信息有換行報錯
                    remark = remark.Replace("\r\n", "<BR/>");
                    body += "<TR>";
                    body += "<TD>";
                    body += SysMsg.GetSystemMessage((SYS_LANGUAGE)(((object[])(clientInfo[0]))[0]), "FLRuntime", "InstanceManager", _description);
                    body += "</TD>";
                    body += "<TD  COLSPAN=7>";
                    body += string.IsNullOrEmpty(remark) ? "&nbsp;" : remark;
                    body += "</TD>";
                    body += "</TR>";
                }

                XmlNode nodeDateTime = doc.ChildNodes[0].SelectSingleNode("DateTime");
                if ((nodeDateTime != null && Convert.ToBoolean(nodeDateTime.InnerText)) || nodeDateTime == null)
                {
                    body += "<TR>";
                    body += "<TD>";
                    body += SysMsg.GetSystemMessage((SYS_LANGUAGE)(((object[])(clientInfo[0]))[0]), "FLRuntime", "InstanceManager", _dateTime);
                    body += "</TD>";
                    body += "<TD  COLSPAN=7>";
                    body += DateTime.Now.ToString();
                    body += "</TD>";
                    body += "</TR>";
                }

                XmlNode nodeHyperLink = doc.ChildNodes[0].SelectSingleNode("HyperLink");
                if ((nodeHyperLink != null && Convert.ToBoolean(nodeHyperLink.InnerText)) || nodeHyperLink == null)
                {
                    string webUrl = flInstance.GetWebUrl();
                    if (webUrl != null && webUrl != "0" && !string.IsNullOrEmpty(wfn))
                    {
                        List<object> objs = new List<object>();
                        string[] webFormNames = wfn.Split('.');
                        if (webFormNames.Length >= 2)
                        {
                            objs.Add(HttpUtility.UrlEncode(webFormNames[0]));
                            objs.Add(HttpUtility.UrlEncode(webFormNames[1]) + ".aspx");
                            objs.Add(HttpUtility.UrlEncode(flInstance.FLInstanceId.ToString()));
                            objs.Add(HttpUtility.UrlEncode((flInstance.CurrentFLActivity == null ? string.Empty : flInstance.CurrentFLActivity.Name) + ";" + nextFLActivity.Name));
                            objs.Add(HttpUtility.UrlEncode(keyValues[1].ToString()));
                            objs.Add(HttpUtility.UrlEncode(((int)nm).ToString()));
                            objs.Add(HttpUtility.UrlEncode(((int)fnm).ToString()));
                            objs.Add(HttpUtility.UrlEncode(users));
                            objs.Add(plusApprove);
                            objs.Add(plusApprove == 1 ? "A" : "");

                            if (webUrl != null && webUrl != string.Empty)
                            {
                                webUrl = string.Format(webUrl, objs.ToArray());
                            }
                        }

                        body += "<TR>";
                        body += "<TD>";
                        body += SysMsg.GetSystemMessage((SYS_LANGUAGE)(((object[])(clientInfo[0]))[0]), "FLRuntime", "InstanceManager", _hyperLink);
                        body += "</TD>";
                        body += "<TD  COLSPAN=7>";
                        body += "<a href=" + webUrl + " target='_blank'>" + SysMsg.GetSystemMessage((SYS_LANGUAGE)(((object[])(clientInfo[0]))[0]), "FLRuntime", "InstanceManager", _hyperLink2) + "</a>";
                        body += "</TD>";
                        body += "</TR>";
                    }
                }

                XmlNode nodeComment = doc.ChildNodes[0].SelectSingleNode("Comment");
                if ((nodeComment != null && Convert.ToBoolean(nodeComment.InnerText)) || nodeComment == null)
                {
                    body += GetComments(flInstance.FLInstanceId.ToString(), clientInfo);
                }

                body += "</TABLE>";

                //---------------------------------------------------------------

                string subject = string.Empty;

                XmlNode nodeFlowName2 = doc.ChildNodes[0].SelectSingleNode("FlowName2");
                if ((nodeFlowName2 != null && Convert.ToBoolean(nodeFlowName2.InnerText)) || nodeFlowName2 == null)
                {
                    subject += flowDesc + "-";
                }

                XmlNode nodeActivityName2 = doc.ChildNodes[0].SelectSingleNode("ActivityName2");
                if ((nodeActivityName2 != null && Convert.ToBoolean(nodeActivityName2.InnerText)) || nodeActivityName2 == null)
                {
                    subject += nextFLActivity.Name;
                }

                XmlNode nodeDescription2 = doc.ChildNodes[0].SelectSingleNode("Description2");
                if ((nodeDescription2 != null && Convert.ToBoolean(nodeDescription2.InnerText)) || nodeDescription2 == null)
                {
                    string remark = flInstance.FLFlag == 'X' ? "Reject(system)" : flInstanceParms[4].ToString();
                    //意見信息有換行報錯
                    remark = remark.Replace("\r\n", " ");
                    if (subject.Length != 0)
                    {
                        subject += ",";
                    }

                    subject += remark;
                }

                XmlNode nodeSender2 = doc.ChildNodes[0].SelectSingleNode("Sender2");
                if ((nodeSender2 != null && Convert.ToBoolean(nodeSender2.InnerText)) || nodeSender2 == null)
                {
                    if (subject.Length != 0)
                    {
                        subject += ",";
                    }

                    subject += sUserId;
                    subject += "(" + sUserName + ")";
                }

                XmlNode nodeContent2 = doc.ChildNodes[0].SelectSingleNode("Content2");
                if ((nodeContent2 != null && Convert.ToBoolean(nodeContent2.InnerText)) || nodeContent2 == null)
                {
                    if (subject.Length != 0)
                    {
                        subject += ",";
                    }
                    if (string.IsNullOrEmpty(presenationCT))
                    {
                        string presentFields = ((IFLRootActivity)flInstance.RootFLActivity).PresentFields;
                        string keys = keyValues[0].ToString();
                        string presenation = keyValues[1].ToString();
                        presenationCT = Global.GetFormPresentCT(tableName, keys, presenation, presentFields, clientInfo);
                    }
                    subject += presenationCT;
                }


                if (subject.Length == 0 && body.Length == 0)
                {
                    return;
                }

                SmtpClient client = new SmtpClient(smtp);
                client.Timeout = 60000;
                _client = client;

                client.UseDefaultCredentials = true;
                client.Credentials = new NetworkCredential(sendFrom, password);
                client.DeliveryMethod = SmtpDeliveryMethod.Network;

                MailMessage message = new MailMessage();
                message.SubjectEncoding = Encoding.UTF8;
                message.BodyEncoding = Encoding.UTF8;
                message.From = new MailAddress(sendFrom, "Workflow", System.Text.Encoding.UTF8);
                foreach (string sendTo in sendToes)
                {
                    message.To.Add(new MailAddress(sendTo, sendTo, Encoding.UTF8));
                }
                message.IsBodyHtml = true;
                message.Subject = subject;
                message.Body = body;
                _message = message;

                Thread thread = new Thread(new ThreadStart(SendMail));
                DateTime d1 = DateTime.Now;
                thread.Start();
                DateTime d2 = DateTime.Now;

                //Console.Write("XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX:{0}", ((TimeSpan)(d2 - d1)).TotalMilliseconds);

                //try
                //{
                //    //DateTime d1 = DateTime.Now;
                //    //client.Send(message);
                //    //DateTime d2 = DateTime.Now;

                //    //Console.Write("XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX:{0}", ((TimeSpan)(d2 - d1)).TotalMilliseconds);
                //}
                //catch
                //{

                //}
            }
        }

        /// <summary>
        /// 发送Email
        /// </summary>
        private static void SendMail()
        {
            StringBuilder title = new StringBuilder("To:");
            foreach (MailAddress address in _message.To)
	        {
		        title.Append(address.Address);
                title.Append(";");
	        }
            if(title.Length> 64)
            {
                title.Remove(64, title.Length - 64);
            }
            string description = _message.Subject;
            if(description.Length > 128)
            {
                description = description.Remove(128, description.Length - 128);
            }
            try
            {
                _client.Send(_message);
                if (SysEEPLogService.Enable)
                {
                    SysEEPLog log = new SysEEPLog(null, SysEEPLog.LogStyleType.Email, SysEEPLog.LogTypeType.Normal
                        , DateTime.Now, title.ToString(), description );
                    log.Log();
                }
            }
            catch
            {
                if (SysEEPLogService.Enable)
                {
                    SysEEPLog log = new SysEEPLog(null, SysEEPLog.LogStyleType.Email, SysEEPLog.LogTypeType.Warning
                        , DateTime.Now, title.ToString() , description);
                    log.Log();
                }
            }
        }

        /// <summary>
        /// 取得密码
        /// </summary>
        /// <param name="s">加密后的密码</param>
        /// <returns></returns>
        private static string GetPwdString(string s)
        {
            string sRet = "";
            for (int i = 0; i < s.Length; i++)
            {
                sRet = sRet + (char)(((int)(s[s.Length - 1 - i])) ^ s.Length);
            }
            return sRet;
        }
    }
}
